
import { PASS } from '../config/constants.js'
import { getRefershToken, removeRefershToken, setAccessToken, setRefershToken } from '../config/storage'
import { getToken } from '@/apis/index.js'
import router from '@/router/index.js';
import { loginData } from '@/types/index.js'
import type { AxiosRequestConfig } from 'axios';
import { showDialog } from 'vant';
let subsequent: AxiosRequestConfig[] = []
let flag = false // 设置开关，保证一次只能请求一次短token，防止客户多此操作，多次请求

/*把过期请求添加在数组中*/
export const addRequest = (request: any) => {
    subsequent.push(request)
}

/*调用过期请求*/
export const retryRequest = () => {
    console.log('重新请求上次中断的数据');
    subsequent.forEach((request: any) => request());
    subsequent = []
}

/*短token过期，携带token去重新请求token*/
export const refreshToken = async () => {
    if (!flag) {
        flag = true;
        let r_tk = getRefershToken() // 获取长token
        if (r_tk) {
            let res = await getToken({
                'Content-Type': 'application/json', //设置请求头请求格式为JSON
                [PASS]: r_tk   //设置token
            }) as loginData
            //长token失效，退出登录
            if (res.code === 4006) {
                flag = false
                removeRefershToken()
                showDialog({
                    message: '登录已失效，请重新登录',
                }).then(() => {
                    router.push('/login')
                })

            } else if (res.code === 2000) {
                // 存储新的token
                setAccessToken(res.data.accessToken)
                setRefershToken(res.data.refreshToken)
                flag = false
                // 重新请求数据
                retryRequest()
            }

        }
    }
}
